import { reqLogin, reqGetUserInfo, reqGetUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'
import store from '@/store'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken // vuex中存
    setToken(newToken) // 持久化的存
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },

  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login(context, data) {
    const res = await reqLogin(data)
    // const token = res.data.data
    const token = res.data
    context.commit('setToken', token)

    return res // {} => promise
  },
  // 获取用户资料
  async getUserInfo(context) {
    const { data: res1 } = await reqGetUserInfo()
    // console.log(res1)
    const { data: res2 } = await reqGetUserDetail(res1.userId)

    const data = { ...res1, ...res2 }
    context.commit('setUserInfo', data)

    return data // 返回用户的所有信息
  },
  // 退出
  logout(context) {
    // 一般在actions中写异步操作,也可以同步的操作
    // 清除token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('removeUserInfo')

    // 重置路由
    resetRouter()
    // console.log(router.options.routes)

    // // 重置permission中的路由
    store.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
